package com.tomehay.termprojectmanage_server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tomehay.termprojectmanage_server.enums.ResponseCode;
import com.tomehay.termprojectmanage_server.mapper.AllocationMapper;
import com.tomehay.termprojectmanage_server.mapper.ClazzMapper;
import com.tomehay.termprojectmanage_server.mapper.GroupMemberMapper;
import com.tomehay.termprojectmanage_server.pojo.DTO.LoginDto;
import com.tomehay.termprojectmanage_server.pojo.DTO.StudentDTO;
import com.tomehay.termprojectmanage_server.pojo.Model.Clazz;
import com.tomehay.termprojectmanage_server.pojo.Model.GroupMember;
import com.tomehay.termprojectmanage_server.pojo.Model.Student;
import com.tomehay.termprojectmanage_server.mapper.StudentMapper;
import com.tomehay.termprojectmanage_server.pojo.Model.Teacher;
import com.tomehay.termprojectmanage_server.pojo.VO.AllocationVO;
import com.tomehay.termprojectmanage_server.pojo.VO.ResultVO;
import com.tomehay.termprojectmanage_server.pojo.VO.StudentVO;
import com.tomehay.termprojectmanage_server.service.StudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomehay
 * @since 2023-06-20
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {


    @Resource
    StudentMapper studentMapper;

    @Resource
    ClazzMapper clazzMapper;

    @Resource
    GroupMemberMapper groupMemberMapper;

    @Resource
    AllocationMapper allocationMapper;

    @Override
    public void exportExcelModel(HttpServletResponse response) throws IOException {
        //定义路径，下面会根据前端方法传的类型而进行判断，区分选择下载的模板，并给path赋值
        String path = null;

        path = "src/main/resources/quest.xlsx";

        //创建文件对象，传递路径参数
        File file = new File(path);

        //获取文件名
        String filename1 = file.getName();

        //创建缓冲流
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        //读操作
        fis.read(buffer);
        //关流
        fis.close();
        //设置响应信息 (响应编码等)
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename1.getBytes(), "iso-8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //响应输出流
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        //写操作
        toClient.write(buffer);
        //刷新
        toClient.flush();
        //关流
        toClient.close();
    }

    @Override
    public ResultVO<Void> BatchAddStudents(MultipartFile multipartFile) {
        Map map = new HashMap<>();
        List<Student> studentList = new ArrayList<>();

        List<Clazz> clazzList = clazzMapper.selectList(null);
        for (Clazz clazz : clazzList) {
            map.put(clazz.getClazzNo(),clazz.getId());
        }

        try{
            InputStream inputStream = multipartFile.getInputStream();
            EasyExcel.read(inputStream, StudentDTO.class,new AnalysisEventListener<StudentDTO>() {
                // 每解析一行数据,该方法会被调用一次
                @Override
                public void invoke(StudentDTO student, AnalysisContext analysisContext) {
                    System.out.println("解析数据为:" + student.toString());
                    Student stu = new Student();
                    stu.setName(student.getName());
                    stu.setStudentNo(student.getStudentNo());
                    stu.setEmail(student.getEmail());
                    stu.setPassword("123456");
                    stu.setCreateTime(LocalDateTime.now());
                    stu.setClazzId(String.valueOf(map.get(student.getClazz_no())));
                    studentList.add(stu);
                }

                // 全部解析完成被调用
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    studentMapper.insertBatchSomeColumn(studentList);
                    Clazz.upDateStudentCount(studentMapper,clazzMapper);
                    System.out.println("录入完成...");
                }
            }).sheet().doRead();

        } catch (IOException e){
            e.printStackTrace();
        }

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<List<Student>> GetStudentsByClazzID(int clazzId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clazz_id",clazzId);
        List<Student> studentList = studentMapper.selectList(queryWrapper);
        return new ResultVO<>(ResponseCode.auto(studentList),studentList);
    }

    @Override
    public ResultVO<Void> CreateStudent(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setPassword("123456");
        studentMapper.insert(student);
        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> UpdateStudent(Student student) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_no",student.getStudentNo());
        studentMapper.update(student,queryWrapper);
        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> RemoveStudent(int id) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        studentMapper.delete(queryWrapper);

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<StudentVO> Login(LoginDto logindto){
        if(StringUtils.isEmpty(logindto.getAccount()) || StringUtils.isEmpty(logindto.getPassword())){
            return new ResultVO<>(ResponseCode.errorOf("用户名或密码不能为空!"));
        }

        logindto.setAccount(logindto.getAccount().trim());
        logindto.setPassword(logindto.getPassword().trim());

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_no",logindto.getAccount());
        Student student = studentMapper.selectOne(queryWrapper);

        if(student==null){
            return new ResultVO<>(ResponseCode.errorOf("用户不存在!"));
        }

        if(!student.getPassword().equals(logindto.getPassword())){
            return new ResultVO<>(ResponseCode.errorOf("密码错误"));
        }

        StudentVO studentVO = new StudentVO();
        BeanUtil.copyProperties(student,studentVO);

        QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("student_id",student.getId());
        List<GroupMember> groupMembers = groupMemberMapper.selectList(groupMemberQueryWrapper);
        List<AllocationVO> allocationVOS;
        for (GroupMember groupMember : groupMembers) {
            if (groupMember.getIsLeader()==1){
                studentVO.setIsLeader(1);
            }
            allocationVOS = allocationMapper.getAllocationVOByGroupId(groupMember.getGroupId());

            for (AllocationVO allocationVO : allocationVOS) {
                allocationVO.setGroupMembers(
                        GroupMember.GetMembers(groupMemberMapper,
                                allocationVO.getGroupId(),
                                studentMapper)
                );
            }

            studentVO.getAllocationVOS().addAll(allocationVOS);
        }

        return new ResultVO<>(ResponseCode.OK,studentVO);
    }



}
